﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using SF.DBUtility;//Please add references
namespace SF.DAL
{
	/// <summary>
	/// 数据访问类:sf_goods_types
	/// </summary>
	public partial class sf_goods_types
	{
		public sf_goods_types()
		{}
		#region  BasicMethod

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(long id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from sf_goods_types");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
            parameters[0].Value = id;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string name,string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from sf_goods_types");
            strSql.Append(" where name=@name");
            if (where != "")
            {
                strSql.Append(" and " + where);
            }
            SqlParameter[] parameters = {
					new SqlParameter("@name", SqlDbType.VarChar,50)
			};
            parameters[0].Value = name;
            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 查询商品分类编号是否存在该记录
        /// </summary>
        public bool ExistsNum(string name, string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from sf_goods_types");
            strSql.Append(" where typeNum=@typeNum ");
            if (where != "")
            {
                strSql.Append(" and " + where);
            }
            SqlParameter[] parameters = {
					new SqlParameter("@typeNum", SqlDbType.VarChar,50)};
            parameters[0].Value = name;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

		/// <summary>
        /// 增加一条数据[事务]
		/// </summary>
		public long Add(SF.Model.sf_goods_types model)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        #region add data
                        string sql = @"insert into [sf_goods_types] ([busnieseNum],[appNum],[templatesNum],[typeNum],
                                     [fatherId],[name],[remark],[sort],[class_layer],[class_list],[pics],[isShow],[goodsTypeNum])
                                      values (@busnieseNum,@appNum,@templatesNum,@typeNum,@fatherId,@name,@remark,@sort,@class_layer,@class_list,@pics,@isShow,@goodsTypeNum);
                                     select @@IDENTITY";
                        SqlParameter[] parameters = new SqlParameter[] {
                            new SqlParameter("@busnieseNum",model.busnieseNum),
                            new SqlParameter("@appNum",model.appNum),
                            new SqlParameter("@templatesNum",model.templatesNum),
                            new SqlParameter("@fatherId",model.fatherId),
                            new SqlParameter("@name",model.name),
                            new SqlParameter("@remark",model.remark),
                            new SqlParameter("@sort",model.sort),
                            new SqlParameter("@class_layer",model.class_layer),
                            new SqlParameter("@class_list",model.class_list),
                            new SqlParameter("@typeNum",model.typeNum),
                            new SqlParameter("@pics",model.pics),
                            new SqlParameter("@isShow",model.isShow),
                            new SqlParameter("@goodsTypeNum",model.goodsTypeNum)
                        
                        };
                        //**增加数据
                        object obj = DbHelperSQL.GetSingle(conn, trans, sql, parameters); //带事务 
                        #endregion
                        #region update class_layer
                        model.id = Convert.ToInt32(obj);
                        if (model.fatherId > 0)
                        {
                            Model.sf_goods_types model2 = GetModel(conn, trans,Convert.ToInt32(model.fatherId)); //带事务
                            model.class_list = model2.class_list + model.id + ",";
                            model.class_layer = model2.class_layer + 1;
                        }
                        else
                        {
                            model.class_list = "," + model.id + ",";
                            model.class_layer = 1;
                        }
                        //修改节点列表和深度
                        DbHelperSQL.ExecuteSql(conn, trans, "update sf_goods_types set class_list='" + model.class_list + "', class_layer=" + model.class_layer + " where id=" + model.id); //带事务
                        //如无异常则提交事务
                        trans.Commit();
                        #endregion
                    }
                    catch
                    {
                        trans.Rollback();
                        return 0;
                    }
                }
            }
            return model.id;
		}
		/// <summary>
        /// 更新一条数据[事务]
		/// </summary>
		public bool Update(SF.Model.sf_goods_types model)
		{
            Model.sf_goods_types oldModel = GetModel(model.id); //旧的数据
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        #region update class_layer
                        //先判断选中的父节点是否被包含
                        if (IsContainNode(model.id, model.fatherId))
                        {
                            //查找旧父节点数据
                            string class_list = "," + model.fatherId + ",";
                            int class_layer = 1;
                            if (oldModel.fatherId > 0)
                            {
                                Model.sf_goods_types oldParentModel =
                                    GetModel(conn, trans, oldModel.fatherId); //带事务
                                class_list = oldParentModel.class_list
                                    + model.fatherId + ",";
                                class_layer = Convert.ToInt32(oldParentModel.class_layer) + 1;
                            }
                            //先提升选中的父节点
                            DbHelperSQL.ExecuteSql(conn, trans, "update sf_goods_types set fatherId=" + oldModel.fatherId + ",class_list='" + class_list + "', class_layer=" + class_layer + " where id=" + model.fatherId); //带事务
                            UpdateChilds(conn, trans, model.fatherId); //带事务
                        }
                        //更新子节点
                        if (model.fatherId > 0)
                        {
                            Model.sf_goods_types model2 = GetModel(conn, trans,model.fatherId); //带事务
                            model.class_list = model2.class_list + model.id + ",";
                            model.class_layer = model2.class_layer + 1;
                        }
                        else
                        {
                            model.class_list = "," + model.id + ",";
                            model.class_layer = 1;
                        }
                        #endregion
                        #region update data
                        String sql = @"update [sf_goods_types]  set [busnieseNum] = @busnieseNum,[appNum] = @appNum,
                                [templatesNum] = @templatesNum,
                                [typeNum] = @typeNum,
                                [fatherId] = @fatherId,
                                [name] = @name,
                                [remark] = @remark,
                                [sort] = @sort,
                                [class_layer] = @class_layer,
                                [class_list] = @class_list,
                                [pics] = @pics,
                                [isShow] = @isShow,
                                [goodsTypeNum] = @goodsTypeNum
                              where [id]=@id";
                        SqlParameter[] parameters = new SqlParameter[] {
                                new SqlParameter("@id",model.id),
                                new SqlParameter("@busnieseNum",model.busnieseNum),
                                new SqlParameter("@appNum",model.appNum),
                                new SqlParameter("@templatesNum",model.templatesNum),
                                new SqlParameter("@fatherId",model.fatherId),
                                new SqlParameter("@name",model.name),
                                new SqlParameter("@remark",model.remark),
                                new SqlParameter("@sort",model.sort),
                                new SqlParameter("@class_layer",model.class_layer),
                                new SqlParameter("@class_list",model.class_list),
                                new SqlParameter("@typeNum",model.typeNum),
                                new SqlParameter("@pics",model.pics),
                                new SqlParameter("@isShow",model.isShow),
                                new SqlParameter("@goodsTypeNum",model.goodsTypeNum)
                             };
                        DbHelperSQL.ExecuteSql(conn, trans, sql, parameters);
                        //更新子节点
                        UpdateChilds(conn, trans, model.id);
                        trans.Commit();
                        #endregion
                    }
                    catch (Exception)
                    {
                        trans.Rollback();
                        return false;
                    }
                }
            }
            return true;
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(long id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from sf_goods_types ");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
			parameters[0].Value = id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string idlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from sf_goods_types ");
			strSql.Append(" where id in ("+idlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


        /// <summary>
        /// 得到一个对象实体(重载，带事务)
        /// </summary>
        public Model.sf_goods_types GetModel(SqlConnection conn, SqlTransaction trans, long id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  * from sf_goods_types ");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)};
            parameters[0].Value = id;

            Model.sf_goods_types model = new Model.sf_goods_types();
            DataSet ds = DbHelperSQL.Query(conn, trans, strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public SF.Model.sf_goods_types GetModel(long id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 id,busnieseNum,appNum,templatesNum,typeNum,fatherId,name,sort,remark,class_layer,class_list,pics,isShow,goodsTypeNum from sf_goods_types ");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
			parameters[0].Value = id;

			SF.Model.sf_goods_types model=new SF.Model.sf_goods_types();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.sf_goods_types GetModel(string typeNum,string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  * from  sf_goods_types ");
            strSql.Append(" where typeNum=@typeNum");
            SqlParameter[] parameters = {
					new SqlParameter("@typeNum", SqlDbType.NVarChar,50)};
            parameters[0].Value = typeNum;
            if (where!="")
            {
                strSql.Append(" and " + where);
            }

            Model.sf_goods_types model = new Model.sf_goods_types();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public SF.Model.sf_goods_types DataRowToModel(DataRow row)
		{
			SF.Model.sf_goods_types model=new SF.Model.sf_goods_types();
			if (row != null)
			{
				if(row["id"]!=null && row["id"].ToString()!="")
				{
					model.id=long.Parse(row["id"].ToString());
				}
				if(row["busnieseNum"]!=null)
				{
					model.busnieseNum=row["busnieseNum"].ToString();
				}
				if(row["appNum"]!=null)
				{
					model.appNum=row["appNum"].ToString();
				}
				if(row["templatesNum"]!=null)
				{
					model.templatesNum=row["templatesNum"].ToString();
				}
				if(row["typeNum"]!=null)
				{
					model.typeNum=row["typeNum"].ToString();
				}
				if(row["fatherId"]!=null && row["fatherId"].ToString()!="")
				{
					model.fatherId=int.Parse(row["fatherId"].ToString());
				}
				if(row["name"]!=null)
				{
					model.name=row["name"].ToString();
				}
				if(row["sort"]!=null && row["sort"].ToString()!="")
				{
					model.sort=int.Parse(row["sort"].ToString());
				}
				if(row["remark"]!=null)
				{
					model.remark=row["remark"].ToString();
				}
				if(row["class_layer"]!=null && row["class_layer"].ToString()!="")
				{
					model.class_layer=int.Parse(row["class_layer"].ToString());
				}
				if(row["class_list"]!=null)
				{
					model.class_list=row["class_list"].ToString();
				}
				if(row["pics"]!=null)
				{
					model.pics=row["pics"].ToString();
				}
				if(row["isShow"]!=null && row["isShow"].ToString()!="")
				{
					model.isShow=int.Parse(row["isShow"].ToString());
				}
				if(row["goodsTypeNum"]!=null)
				{
					model.goodsTypeNum= row["goodsTypeNum"].ToString();
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select id,busnieseNum,appNum,templatesNum,typeNum,fatherId,name,sort,remark,class_layer,class_list,pics,isShow,goodsTypeNum ");
			strSql.Append(" FROM sf_goods_types ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" id,busnieseNum,appNum,templatesNum,typeNum,fatherId,name,sort,remark,class_layer,class_list,pics,isShow,goodsTypeNum ");
			strSql.Append(" FROM sf_goods_types ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM sf_goods_types ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.id desc");
			}
			strSql.Append(")AS Row, T.*  from sf_goods_types T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "sf_goods_types";
			parameters[1].Value = "id";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(long id, string strValue)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("update sf_goods_types set " + strValue);
                strSql.Append(" where id=" + id);
                DbHelperSQL.ExecuteSql(strSql.ToString());
                return true;
            }
            catch (Exception)
            {
            }
            return false;
        }


        /// <summary>
        /// 验证节点是否被包含
        /// </summary>
        /// <param name="id">待查询的节点</param>
        /// <param name="fatherID">父节点</param>
        /// <returns></returns>
        private bool IsContainNode(long id, long fatherId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from sf_goods_types ");
            strSql.Append(" where class_list like '%," + id + ",%' and id=" + fatherId);
            return DbHelperSQL.Exists(strSql.ToString());
        }

        /// <summary>
        /// 修改子节点的ID列表及深度（自身迭代）
        /// </summary>
        /// <param name="fatherID"></param>
        private void UpdateChilds(SqlConnection conn, SqlTransaction trans, long fatherId)
        {
            //查找父节点信息
            Model.sf_goods_types model = GetModel(conn, trans, fatherId);
            if (model != null)
            {
                //查找子节点
                string strSql = "select id from  sf_goods_types where fatherId=" + fatherId;
                DataSet ds = DbHelperSQL.Query(conn, trans, strSql); //带事务
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //修改子节点的ID列表及深度
                    int id = int.Parse(dr["id"].ToString());
                    string class_list = model.class_list + id + ",";
                    int class_layer = Convert.ToInt32(model.class_layer) + 1;
                    DbHelperSQL.ExecuteSql(conn, trans, "update sf_goods_types set class_list='" + class_list + "', class_layer=" + class_layer + " where id=" + id); //带事务

                    //调用自身迭代
                    this.UpdateChilds(conn, trans, id); //带事务
                }
            }
        }


        /// <summary>
        /// 取得所有类别列表
        /// </summary>
        /// <param name="fatherID">父ID</param>
        /// <returns></returns>
        public DataTable GetList(long fatherID, string strWhere)
        {
            String strSql = "select * from sf_goods_types {0} order by sort asc,id desc";
            strSql = String.Format(strSql, String.IsNullOrEmpty(strWhere) ? "" : " where " + strWhere);
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            DataTable oldData = ds.Tables[0] as DataTable;
            if (oldData == null)
            {
                return null;
            }
            //复制结构
            DataTable newData = oldData.Clone();
            //调用迭代组合成DAGATABLE
            GetChilds(oldData, newData, fatherID);
            return newData;
        }


        /// <summary>
        /// 从内存中取得所有下级类别列表（自身迭代）
        /// </summary>
        private void GetChilds(DataTable oldData, DataTable newData, long fatherID)
        {
            DataRow[] dr = oldData.Select("fatherId=" + fatherID);
            for (int i = 0; i < dr.Length; i++)
            {
                //添加一行数据
                DataRow row = newData.NewRow();
                row["id"] = long.Parse(dr[i]["id"].ToString());
                row["typeNum"] = dr[i]["typeNum"].ToString();
                row["fatherId"] = long.Parse(dr[i]["fatherId"].ToString());
                row["name"] = dr[i]["name"].ToString();
                row["remark"] = dr[i]["remark"].ToString();
                row["sort"] = int.Parse(dr[i]["sort"].ToString());
                row["class_layer"] = int.Parse(dr[i]["class_layer"].ToString());
                row["pics"] = dr[i]["pics"].ToString();
                row["isShow"] = dr[i]["isShow"].ToString();
                row["goodsTypeNum"] = dr[i]["goodsTypeNum"].ToString();
                newData.Rows.Add(row);
                //调用自身迭代
                this.GetChilds(oldData, newData, int.Parse(dr[i]["id"].ToString()));
            }
        }


        /// <summary>
        /// 取得所有类别列表
        /// </summary>
        /// <param name="fatherID">父ID</param>
        /// <returns></returns>
        public DataTable GetList(long fatherID, string strWhere, int count)
        {
            String strSql = "select * from sf_goods_types {0} order by sort asc,id desc";
            strSql = String.Format(strSql, String.IsNullOrEmpty(strWhere) ? "" : " where " + strWhere);
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            DataTable oldData = ds.Tables[0] as DataTable;
            if (oldData == null)
            {
                return null;
            }
            //复制结构
            DataTable newData = oldData.Clone();
            //调用迭代组合成DAGATABLE
            GetChilds(oldData, newData, fatherID, count);
            return newData;
        }
        /// <summary>
        /// 从内存中取得所有下级类别列表（自身迭代）
        /// </summary>
        private void GetChilds(DataTable oldData, DataTable newData, long fatherID, int count)
        {
            DataRow[] dr = oldData.Select("fatherId=" + fatherID);
            for (int i = 0; i < dr.Length; i++)
            {
                //添加一行数据
                DataRow row = newData.NewRow();
                row["id"] = int.Parse(dr[i]["id"].ToString());
                row["typeNum"] = dr[i]["typeNum"].ToString();
                row["fatherId"] = int.Parse(dr[i]["fatherID"].ToString());
                row["name"] = dr[i]["name"].ToString();
                row["remark"] = dr[i]["remark"].ToString();
                row["sort"] = int.Parse(dr[i]["sort"].ToString());
                row["class_layer"] = int.Parse(dr[i]["class_layer"].ToString());
                row["pics"] = dr[i]["pics"].ToString();
                row["isShow"] = dr[i]["isShow"].ToString();
                row["goodsTypeNum"] = dr[i]["goodsTypeNum"].ToString();
                newData.Rows.Add(row);
                //调用自身迭代
                if (int.Parse(dr[i]["class_layer"].ToString()) < count)
                {
                    this.GetChilds(oldData, newData, int.Parse(dr[i]["id"].ToString()), count);
                }
            }
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(string strValue, string where)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("update sf_goods_types set " + strValue);
                strSql.Append(" where " + where);
                DbHelperSQL.ExecuteSql(strSql.ToString());
                return true;
            }
            catch (Exception)
            {
            }
            return false;
        }
		#endregion  ExtensionMethod
	}
}

